package com.alibaba.cloud.anno;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.cloud.utils.RegexpUtils;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;


/**
 * @author zhb131678362@163.com
 * @Description: 描述作用
 * @date 2018/11/2614:16
 */
public class IsEmailValidator implements ConstraintValidator<IsEmail, String> {
    
    /** The required. */
    private boolean required = false;

    /**
     * Initialize.
     *
     * @param constraintAnnotation the constraint annotation
     */
    @Override
    public void initialize(IsEmail constraintAnnotation) {
        required = constraintAnnotation.require();
    }

    /**
     * Checks if is valid.
     *
     * @param value the value
     * @param context the context
     * @return true, if is valid
     */
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (required) {
            return RegexpUtils.isEmail(value);
        } else {
            if (StringUtils.isEmpty(value)) {
                return true;
            } else {
                return RegexpUtils.isEmail(value);
            }
        }
    }
}
